package com.mgq.juc.design.alternate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MaGuangQi
 * 使用reentrantLock来实现
 * reentrantLock提供了condition.我们可以让不同的变量去各自的休息室(condition)去休息
 * 比如a去a休息室休息
 * b去b休息室休息
 * c去c休息室休息
 * @date 2021-12-17 14:17
 **/
public class TestAwaitSignal {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        Thread t1 = new Thread(() -> {
            awaitSignal.print("a", a, b);

        }, "t1");
        Thread t2 = new Thread(() -> {
            awaitSignal.print("b", b, c);
        }, "t2");
        Thread t3 = new Thread(() -> {
            awaitSignal.print("c", c, a);
        }, "t3");

        t1.start();
        t2.start();
        t3.start();
        //让他们都先await()

        Thread.sleep(1000);
        System.out.println("开始............");
        //需要等待一会儿,否则主线程signal()执行的时候,a线程可能还没启动,导致没有唤醒a
        awaitSignal.lock();
        try {
            a.signal();
        } finally {
            awaitSignal.unlock();
        }
    }
}

class AwaitSignal extends ReentrantLock {

    private int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    /**
     * @param str     需要打印的字符
     * @param current 绑定的condition
     * @param next    需要唤醒的下一个condition
     */
    public void print(String str, Condition current, Condition next) {
        for (int i = 0; i < loopNumber; i++) {
            this.lock();
            try {
                //首先所有的thread都等待,由主线程唤醒其中一个.
                //await会释放锁
                current.await();
                System.out.print(str);
                //唤醒下一个线程
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                this.unlock();
            }
        }
    }
}
